package cn.xxy.utils;

import cn.xxy.beans.DataSourceConfig;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;

/**
 * @author xxy
 * @date 2024/11/20
 */
public class ConnUtils {
    private static final HashMap<String, DataSourceConfig> dataSourceMap = new HashMap<>();
//    static{
//        registerDataSource("mysql","com.mysql.cj.jdbc.Driver", "jdbc:mysql://60.204.242.253:3306/dbapi?useSSL=false&useUnicode=true&characterEncoding=utf-8","admin", "password123");
//        registerDataSource("oracle","oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:@10.241.111.11/orcl","fghis5", "fg3602001");
//        registerDataSource("sqlserver","com.microsoft.sqlserver.jdbc.SQLServerDriver", "jdbc:sqlserver://localhost:1433; DatabaseName=test;trustServerCertificate=true","sa", "123456");
//        registerDataSource("dm","dm.jdbc.driver.DmDriver", "jdbc:dm://10.1.94.194:5237","TEST", "test");
//        registerDataSource("postgresql","org.postgresql.Driver", "jdbc:postgresql://106.54.238.19:5432/postgres","teslamate", "teslamate");
//        registerDataSource("kingbase8","com.kingbase8.Driver", "jdbc:kingbase8://10.241.111.11:9321/test","system", "system");
//        registerDataSourceFromFile("jdbcs.xml");
//    }
    /**
     * @param configFile 配置文件的名字
     */
    public static void registerDataSourceFromFile(String configFile){
        SAXReader saxReader = new SAXReader();
        //读取指定的配置文件
        try {
            Document document = saxReader.read(ConnUtils.class.getClassLoader().getResourceAsStream(configFile));
            //获取根元素
            Element rootElement = document.getRootElement();
            //读取所有的环境配置
            Element envsElement = rootElement.element("connectionStrings");
            //读取所有的环境
            List<Element> elements = envsElement.elements("connectionString");
            DataSourceConfig config;
            for(Element element: elements){
                //id
                String envId = element.attributeValue("id").trim();
                if(envId.isEmpty()) {
                    envId = element.attributeValue("name").trim();
                }
                String dataSourceAdapter = element.elementText("dataSourceAdapter").trim();
                if(dataSourceAdapter.isEmpty()) {
                    dataSourceAdapter="cn.xxy.datasource.NoneDataSourceAdapter";
                }
                //
                String driverClassName = element.elementText("driverClassName");
                String user = element.elementText("user");
                String password = element.elementText("password");
                String url = element.elementText("url");

                config = new DataSourceConfig();
                config.setDataSourceAdapter(dataSourceAdapter);
                config.setDbName(envId);
                config.setJdbcUrl(url);
                config.setDriverClass(driverClassName);
                config.setUsername(user);
                config.setPassword(password);

                //获取其他的配置信息
                List<Element> subelements = element.elements();
                for(Element subelement: subelements) {
                    String name = subelement.getName().trim();
                    if (name.equalsIgnoreCase("id") || name.equalsIgnoreCase("name")
                            || name.equalsIgnoreCase("dataSourceAdapter")
                            || name.equalsIgnoreCase("driverClassName") || name.equalsIgnoreCase("url")
                            || name.equalsIgnoreCase("password") || name.equalsIgnoreCase("user")) {
                        continue;
                    }
                    config.setProperty(name, subelement.getText());
                }
                registerDataSource(envId, config);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }
    /**
     * 注册数据源
     * @param dbName 连接名字
     * @param config 数据源配置
     */
    public static boolean registerDataSource(String dbName,DataSourceConfig config) {
        if (dbName.isEmpty()) {
            throw new RuntimeException("dbName 不能为空");
        }

        if (config == null || config.getDriverClass().isEmpty()) {
            throw new RuntimeException("properties 不能为空 for:【" + dbName + "】");
        }
        config.setDbName(dbName);
        dataSourceMap.put(dbName, config);
        return true;
    }
    /**
     * 注册数据源
     * @param dbName 连接名字
     * @param driver 数据源驱动
     * @param url 数据源连接地址
     * @param user 数据源用户名
     * @param password 数据源密码
     */
    public static void registerDataSource(String dbName, String driver, String url, String user, String password) {
        registerDataSource(dbName, driver, url, user, password, "cn.xxy.datasource.NoneDataSourceAdapter");
    }
    /**
     * 注册数据源
     * @param dbName 连接名字
     * @param driver 数据源驱动
     * @param url 数据源连接地址
     * @param user 数据源用户名
     * @param password 数据源密码
     */
    public static void registerDataSource(String dbName, String driver, String url, String user, String password, String dataSourceAdapter) {
        if (dbName.isEmpty()) {
            throw new RuntimeException("dbName 不能为空");
        }
        if (driver.isEmpty()) {
            throw new RuntimeException("driver 不能为空");
        }
        if (url.isEmpty()) {
            throw new RuntimeException("url 不能为空");
        }
        if (dataSourceAdapter == null || dataSourceAdapter.isEmpty()) {
            dataSourceAdapter = "cn.xxy.datasource.NoneDataSourceAdapter";
        }
        DataSourceConfig config = new DataSourceConfig();
        config.setDataSourceAdapter(dataSourceAdapter);
        config.setDbName(dbName);
        config.setJdbcUrl(url);
        config.setDriverClass(driver);
        config.setUsername(user);
        config.setPassword(password);

        dataSourceMap.put(dbName, config);
    }
    /**
     * 获取指定连接名称的数据源
     * @param dbName 连接名字
     */
    public static DataSourceConfig getDataSourceConfig(String dbName) {
        if (dataSourceMap.isEmpty()) {
            throw new RuntimeException("对不起，没有读取到任何的配置信息，请假查是否正确配置");
        }
        DataSourceConfig config = dataSourceMap.get(dbName);
        if (config == null || config.getDriverClass().isEmpty()) {
            registerDataSourceFromFile("jdbcs.xml");
            config = dataSourceMap.get(dbName);
        }
        if (config == null || config.getDriverClass().isEmpty()) {
            throw new RuntimeException("没有读取到对应的配置信息for:【" + dbName + "】");
        }
//        try {//加载驱动
//            Class.forName(config.getDriverClass());
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
        return config;
    }
//    /**
//     * 获取指定连接名称的数据连接
//     * @param dbName 连接名字
//     */
//    public static Connection getConnection(String dbName) {
//        DataSourceConfig config = getDataSourceConfig(dbName);
//        try {//获取连接
//            Properties properties = new Properties();
//            properties.setProperty("driverClassName", config.getDriverClass());
//            properties.setProperty("url", config.getJdbcUrl());
//            properties.setProperty("user", config.getUsername());
//            properties.setProperty("password", config.getPassword());
//            Connection connection = DriverManager.getConnection(config.getJdbcUrl(), properties);
//            return connection;
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//    /**
//     * 获取一个连接名称的数据连接
//     * @param driver 数据源驱动
//     * @param url 数据源连接地址
//     * @param user 数据源用户名
//     * @param password 数据源密码
//     */
//    public static Connection getConnection(String driver, String url, String user, String password) {
//        try {//加载驱动
//            Class.forName(driver);
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
//        try {//获取连接
//            return DriverManager.getConnection(url, user, password);
//        } catch(SQLException e) {
//            throw new RuntimeException("Get connection fail.", e);
//        }
//    }

//    public static void main(String[] args) {
//        System.out.println(getConnection("dm"));//oracle,mysql,postgresql
//    }
}
